import React, { useState, useEffect } from "react";
import styles from "../style/scoreDetails.module.css";
import { useNavigate } from "react-router-dom";
import leftImg from "../img/left.png";
import start from "../img/start.png";
import noData from "../img/biudifou.jpg";
import { score_history } from "../api/score";

// 积分记录接口
interface ScoreRecord {
  id: number;
  type: string;
  amount: number;
  description: string;
  created_at: string;
}

// 订单记录接口（已更新为匹配实际API返回的字段）
interface OrderRecord {
  id: number;
  code: string; // 订单编号
  status_title: string; // 订单状态显示文本
  title: string; // 商品名称
  norm: string; // 商品规格
  img: string; // 商品图片
  price: string; // 商品价格（字符串格式）
  num: number; // 购买数量
  createtime: string; // 创建时间
  address: string; // 收货地址
  address_desc: string; // 地址描述
  goods_id: number; // 商品ID
  name: string; // 收货人姓名
  tel: string; // 联系电话
  status: string; // 状态码
}

// API响应接口
interface ApiResponse {
  code: number;
  msg: string;
  data: {
    list: ScoreRecord[] | OrderRecord[];
    total_score?: number;
    earned_score?: number;
    consumed_score?: number;
    expiring_score?: number;
  };
}

const ScoreDetailsPage: React.FC = () => {
  const navigate = useNavigate();
  const [activeTab, setActiveTab] = useState<"score" | "order">("score");
  const [scoreFilter, setScoreFilter] = useState<"all" | "earned" | "consumed">(
    "all"
  );
  const [scoreData, setScoreData] = useState<ScoreRecord[]>([]);
  const [orderData, setOrderData] = useState<OrderRecord[]>([]);
  const [totalScore, setTotalScore] = useState<number>(0);
  const [earnedScore, setEarnedScore] = useState<number>(190);
  const [consumedScore, setConsumedScore] = useState<number>(100);
  const [expiringScore, setExpiringScore] = useState<number>(50);
  const [isLoading, setIsLoading] = useState<boolean>(true);
  const [error, setError] = useState<string | null>(null);

  // 从本地存储获取用户数据
  const user = JSON.parse(localStorage.getItem("user") || "null");
  console.log(user.data.token, "请求头token");
  console.log(user.data.id, "请求id");

  useEffect(() => {
    const fetchScoreData = async () => {
      try {
        setIsLoading(true);
        // 这里保留积分数据的模拟请求，实际项目中应该替换为真实API调用
        const mockScoreData: ApiResponse = {
          code: 1,
          msg: "Success",
          data: {
            list: [
              {
                id: 1,
                type: "earned",
                amount: 20,
                description: "签到积分奖励",
                created_at: "2023-09-02 15:20:04",
              },
            ],
            total_score: 10005,
            earned_score: 190,
            consumed_score: 100,
            expiring_score: 50,
          },
        };

        if (mockScoreData.code === 1) {
          setScoreData(mockScoreData.data.list as ScoreRecord[]);
          setTotalScore(mockScoreData.data.total_score || 0);
          setEarnedScore(mockScoreData.data.earned_score || 0);
          setConsumedScore(mockScoreData.data.consumed_score || 0);
          setExpiringScore(mockScoreData.data.expiring_score || 0);
        } else {
          setError(mockScoreData.msg);
        }
      } catch (err) {
        setError("获取积分数据失败");
        console.error(err);
      } finally {
        setIsLoading(false);
      }
    };

    const fetchOrderData = async () => {
      try {
        const response = await score_history({
          uid: user.data.id,
        });

        console.log(response.data, "积分订单数据");

        if (response.data.code === 1) {
          // 直接使用API返回的数据，不需要转换
          setOrderData(response.data.data.list as OrderRecord[]);
        } else {
          setError(response.data.msg);
        }
      } catch (err) {
        setError("获取订单数据失败");
        console.error(err);
      } finally {
        setIsLoading(false);
      }
    };

    fetchScoreData();
    fetchOrderData();
  }, [scoreFilter]);

  // 切换标签页
  const handleTabChange = (tab: "score" | "order") => {
    setActiveTab(tab);
  };

  // 切换积分筛选条件
  const handleScoreFilterChange = (filter: "all" | "earned" | "consumed") => {
    setScoreFilter(filter);
  };

  // 返回上一页
  const returnLast = () => {
    navigate("/score");
  };

  // 跳转到积分订单详情页面
  const handleOrderClick = (order: OrderRecord) => {
    // 存储订单数据到localStorage
    const orderData = {
      orderID: order.id,
      productName: order.title,
      points: order.price,
      orderTime: order.createtime,
      orderNumber: order.code,
      specification: order.norm,
      productImage: order.img,
      status: order.status_title,
      orderNum: order.num,
    };

    localStorage.setItem("currentOrder", JSON.stringify(orderData));

    // 跳转到订单详情页
    navigate("/Pointsdetails");
  };

  if (isLoading) {
    return <div className={styles.loading}>加载中...</div>;
  }

  if (error) {
    return <div className={styles.error}>{error}</div>;
  }

  return (
    <div className={styles.pageContainer}>
      {/* 顶部标题栏 */}
      <div className={styles.pageHeader}>
        <div className={styles.pageImg} onClick={returnLast}>
          <img src={leftImg} alt="返回" />
        </div>
        <div className={styles.pageText}>积分中心</div>
      </div>

      {/* 积分显示区域 */}
      <div className={styles.scoreDisplay}>
        <div className={styles.scoreLeft}>
          <div className={styles.scoreTop}>
            积分<span className={styles.scoreValue}>{totalScore}</span>
          </div>
          <div className={styles.scoreLabel}>现余积分</div>
        </div>
        <div className={styles.scoreRight}>
          <img src={start} alt="积分图标" />
        </div>
      </div>

      {/* 标签页选择 */}
      <div className={styles.tabContainer}>
        <div
          className={`${styles.tab} ${
            activeTab === "score" ? styles.activeTab : ""
          }`}
          onClick={() => handleTabChange("score")}
        >
          积分收支明细
        </div>
        <div
          className={`${styles.tab} ${
            activeTab === "order" ? styles.activeTab : ""
          }`}
          onClick={() => handleTabChange("order")}
        >
          订单记录
        </div>
      </div>

      {/* 根据活动标签显示内容 */}
      {activeTab === "score" ? (
        <div className={styles.scoreContent}>
          {/* 筛选选项 */}
          <div className={styles.filterOptions}>
            <div
              className={`${styles.filterOption} ${
                scoreFilter === "all" ? styles.activeFilter : ""
              }`}
              onClick={() => handleScoreFilterChange("all")}
            >
              全部
            </div>
            <div
              className={`${styles.filterOption} ${
                scoreFilter === "earned" ? styles.activeFilter : ""
              }`}
              onClick={() => handleScoreFilterChange("earned")}
            >
              已获取
            </div>
            <div
              className={`${styles.filterOption} ${
                scoreFilter === "consumed" ? styles.activeFilter : ""
              }`}
              onClick={() => handleScoreFilterChange("consumed")}
            >
              已消耗
            </div>
          </div>

          {/* 积分摘要 */}
          <div className={styles.scoreSummary}>
            本月获取<span className={styles.earnedScore}>{earnedScore}</span>
            已消耗<span className={styles.consumedScore}>{consumedScore}</span>
          </div>

          {/* 即将过期积分提示 */}
          <div className={styles.expiringPrompt}>
            <div className={styles.promptLeft}>
              本月即将过期{expiringScore}积分
            </div>
            <div className={styles.promptRight}>去使用</div>
          </div>

          {/* 积分记录列表 */}
          {scoreData.length === 0 ? (
            <div className={styles.noData}>暂无数据</div>
          ) : (
            <div className={styles.scoreRecords}>
              {scoreData.map((record) => (
                <div key={record.id} className={styles.scoreRecord}>
                  <div className={styles.recordLeft}>
                    <div className={styles.recordDescription}>
                      {record.description}
                    </div>
                    <div className={styles.recordTime}>{record.created_at}</div>
                  </div>
                  <div className={styles.recordRight}>
                    {record.type === "earned" ? "+" : "-"}
                    {record.amount}
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      ) : (
        <div className={styles.orderContent}>
          {orderData.length === 0 ? (
            <div className={styles.noData}>
              <img src={noData} alt="暂无数据" style={{ width: "100%" }} />
            </div>
          ) : (
            <div className={styles.orderList}>
              {orderData.map((order) => (
                <div
                  key={order.id}
                  onClick={() => handleOrderClick(order)}
                  className={styles.orderItem}
                >
                  {/* 订单头部 */}
                  <div className={styles.orderHeader}>
                    <div className={styles.orderNumber}>
                      订单号: <span>{order.code}</span>
                    </div>
                    <div className={styles.orderStatus}>
                      {order.status_title}
                    </div>
                  </div>

                  {/* 订单详情 */}
                  <div className={styles.orderDetails}>
                    <div className={styles.productImage}>
                      <img src={order.img} alt={order.title} />
                    </div>
                    <div className={styles.productInfo}>
                      <div className={styles.productName}>{order.title}</div>
                      <div className={styles.productDescription}>
                        {order.norm}
                      </div>
                      <div className={styles.orderTime}>{order.createtime}</div>
                    </div>
                    <div className={styles.productPrice}>
                      <div className={styles.price}>{order.price}积分</div>
                      <div className={styles.quantity}>X{order.num}</div>
                    </div>
                  </div>

                  {/* 订单操作按钮 */}
                  <div className={styles.orderActions}>
                    <div className={styles.deleteButton}>删除订单</div>
                    <div className={styles.buyAgainButton}>再次购买</div>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      )}
    </div>
  );
};

export default ScoreDetailsPage;
